/*
 * @Description:权限按钮展示指令
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-26 00:19:51
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2023-09-01 14:37:00
 */
import { useUserStore } from '@/stores/user'

export default (app) => {
	const userStore = useUserStore()
	app.directive('auth', {
		// 当被绑定的元素插入到 DOM 中时……
		mounted: function (el, binding) {
			const permissions = userStore.permissions
			let type = ''
			switch (Object.prototype.toString.call(binding.value)) {
				case '[object Array]':
					type = 'Array'
					break
				case '[object String]':
					type = 'String'
					break
				case '[object Number]':
					type = 'Number'
					break
				default:
					type = ''
					break
			}
			if (type === '') {
				el.parentNode.removeChild(el)
				return
			}
			const waitUse = binding.value.toString()
			if (type == 'Array') {
				const result = binding.value.map((item) => {
					if (Object.prototype.toString.call(item) == '[object String]') {
						let flag = waitUse && permissions ? permissions?.[item.toString()] : true
						if (binding.modifiers.not) {
							flag = !flag
						}
						return flag
					} else {
						return item
					}
				})
				if (result.length > 0 && !result.reduce((a, b) => a && b)) {
					el.parentNode.removeChild(el)
				}
			} else {
				let flag = waitUse && permissions ? permissions?.[waitUse] : true
				if (binding.modifiers.not) {
					flag = !flag
				}
				if (!flag) {
					el.parentNode.removeChild(el)
				}
			}
		},
	})
}
